#region (c) 2009 Abdullin.com and Contributors

// Copyright (c) 2009 Abdullin.com and Contributors
// Site: http://abdullin.com/ncouch
// This code is released under the terms of the new BSD licence

#endregion

using System;
using System.IO;
using NCouch.Rest;

namespace NCouch
{
	public sealed class CouchRestClient
	{
		readonly ISerializer _serializer;
		readonly IRestClient _client;
		readonly Uri _baseUrl;


		internal const string JsonContentType = "application/json";

		public CouchRestClient(ISerializer serializer, IRestClient client, Uri baseUrl)
		{
			_serializer = serializer;
			_client = client;
			_baseUrl = baseUrl;
		}


		internal IRestResponse GetRequest(
			CouchRestMethod method,
			string query,
			Action<CouchRequestSyntax> config)
		{
			var syntax = new CouchRequestSyntax(this, method, query);
			config(syntax);

			

			
			var url = UriCombine(query, _baseUrl);
			var request = new RestRequest(
				url,
				syntax.ContentType,
				syntax.Method.ToString(),
				syntax.Content,
				syntax.Headers);

			var response = _client.GetResponse(request);
			return response;
		}

		static Uri UriCombine(string query, Uri baseUrl)
		{
			var baseUrlString = baseUrl;

			if (!baseUrlString.ToString().EndsWith("/"))
			{
				return new Uri(baseUrl + "/" + query);
			}
			return new Uri(baseUrl + query);
		}

		internal Action<Stream> Serialize<T>(T item)
		{
			return stream => _serializer.Serialize(stream, item);
		}

		internal T Deserialize<T>(IRestResponse response)
		{
			var t = default(T);
			response.RunReader(stream => t = _serializer.Deserialize<T>(stream));
			return t;
		}
	}
}